package service;

import dao.BookMapper;
import dao.ShoppingMapper;
import dao.UserMapper;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import pojo.Book;
import pojo.Shopping;
import pojo.User;
import until.SqlSessionFactoryUtils;

import java.util.List;

public class ShoppingService {
    SqlSessionFactory factory = SqlSessionFactoryUtils.getSqlSessionFactory();

    public List<Shopping> selectShopping(String username){
        //获取Session
        SqlSession sqlSession = factory.openSession();
        //获取Mapper
        ShoppingMapper mapper = sqlSession.getMapper(ShoppingMapper.class);
        return mapper.selectShopping(username);
    }
    public int addShopping(String bookId,String username){
        //获取Session
        SqlSession sqlSession = factory.openSession();
        BookMapper mapper1 = sqlSession.getMapper(BookMapper.class);
        ShoppingMapper mapper3 = sqlSession.getMapper(ShoppingMapper.class);
        UserMapper mapper2 = sqlSession.getMapper(UserMapper.class);
        User user = mapper2.selectUserId(username);
        Book book = mapper1.selectBookDetail(bookId);
//        int i = mapper1.addShopping(user.getId(), book.getName(), book.getAuthor(), book.getPrice(), book.getImageName(),bookId);
        int i = mapper3.addShopping(user.getId(), book.getName(), book.getAuthor(), book.getPrice(), book.getImageName(),bookId);
        // 手动提交事务
        sqlSession.commit();
        return i;
    }

    public int deleteShopping(String id){
        SqlSession sqlSession = factory.openSession();
        ShoppingMapper mapper = sqlSession.getMapper(ShoppingMapper.class);
        int i =  mapper.deleteShopping(id);
        // 手动提交事务
        sqlSession.commit();
        return i;
    }

}
